package com.xx.springboot.controller;

import com.xx.springboot.annotation.Log;
import com.xx.springboot.entity.Blog;
import com.xx.springboot.entity.ResponseBo;
import com.xx.springboot.entity.User;
import com.xx.springboot.service.IBlogService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.sql.Date;


/**
 * <p>
 *     处理管理界面 控制器
 * </p>
 * @author atom.hu
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private IBlogService blogService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * <p>
     *     增加blog
     * </p>
     * @param blog
     * @return
     */
    @RequestMapping("/addBlog")
    @Log("增加博客")
    public ResponseBo addBlog (@Valid Blog blog) {
        User user = (User)SecurityUtils.getSubject().getPrincipal();
        blog.setCreateTime(new Date(System.currentTimeMillis()));
        blog.setIsDelete(0);
        blog.setUserId(user.getId());
        blog.setStatus(1);
        try {
            blogService.save(blog);
            return ResponseBo.ok("添加成功");
        }catch (Exception ex){
            return ResponseBo.error(ex.getMessage());
        }
    }

    /**
     * <p>
     * 逻辑删除 blog
     * </p>
     *
     * @param Id
     * @return
     */
    @PostMapping("/delBlog")
    public ResponseBo removeBlog(Long Id) {
        try {
            if (blogService.removeBlog(Id) == 1) {
                return ResponseBo.ok("删除成功");
            } else {
                return ResponseBo.error();
            }
        } catch (Exception ex) {
            return ResponseBo.error(ex.getMessage());
        }
    }

    @RequestMapping("/test")
    public ResponseBo testRedis() {
        User user = new User();
        user.setUsername("test");
        redisTemplate.opsForValue().set("user", user);
        return ResponseBo.ok(redisTemplate.opsForValue().get("user"));
    }
}
